package com.situ.stl.api;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.situ.stl.util.JsonResult;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    // 从配置文件读取上传目录
    @Value("${upload.location}")
    private String uploadDir;

    // 处理文件上传，使用ResponseEntity包装返回结果
    @PostMapping("/upload")
    public ResponseEntity<JsonResult<?>> uploadFile(
            @RequestParam("file")
            MultipartFile file
    ) {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.ok(JsonResult.fail("上传文件为空"));
        }

        // 2. 生成唯一文件名（避免重复）
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.contains(".")) {
            return ResponseEntity.ok(JsonResult.fail("文件名格式不正确"));
        }

        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + fileExtension;

        // 3. 确保上传目录存在
        File uploadDirectory = new File(uploadDir);
        if (!uploadDirectory.exists() && !uploadDirectory.mkdirs()) {
            return ResponseEntity.ok(JsonResult.fail("无法创建上传目录，请检查权限"));
        }

        // 4. 拼接本地保存路径
        String savePath = uploadDir + fileName;
        File dest = new File(savePath);

        try {
            // 5. 保存文件到本地
            file.transferTo(dest);

            // 6. 返回数据库存储的相对路径
            String dbPath = "/upload/" + fileName;
            return ResponseEntity.ok(JsonResult.success(dbPath));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.ok(JsonResult.fail("文件上传失败：" + e.getMessage()));
        }
    }
}
